package be.ac.ua.ecampus.uacmat;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import be.ac.ua.ecampus.uacmat.entity.Entity;

@WebServlet(description = "Search", urlPatterns = { "/search" })
public class SearchServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public SearchServlet() {
		super();
	}

	public void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}

	public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
		final String search = request.getParameter("search");
		final String resultgroup = request.getParameter("resultgroup");
		
		if ((search == null) || search.isEmpty()) {
			System.out.println("[CMAT WARNING] - [SEARCH] - Empty string given.");
			return;
		}
		QueryHandler queryHandler = new QueryHandler();
		try {
			Collection<Entity> syllabuses = null;
			if (resultgroup.contentEquals("all") || resultgroup.contentEquals("syllabuses")) {
				syllabuses = queryHandler.searchSyllabuses(search);
			}
			
			Collection<Entity> programs = null;
			if (resultgroup.contentEquals("all") || resultgroup.contentEquals("programs")) {
				programs = queryHandler.searchPrograms(search);
			}
			
			Collection<Entity> courses = null;
			if (resultgroup.contentEquals("all") || resultgroup.contentEquals("courses")) {
				courses = queryHandler.searchCourses(search);
			}
			
			request.setAttribute("syllabuses", syllabuses);
			request.setAttribute("programs", programs);
			request.setAttribute("courses", courses);
			request.getRequestDispatcher("/showSearch.jsp").forward(request, response);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}